package com.amat0urheu.aspect;




import com.amat0urheu.annotation.OperateLog;
import com.amat0urheu.pojo.OperationLog;
import com.amat0urheu.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;


@Aspect
@Component
public class SystemLogAspect {
@Autowired
LogService logService;

    @Pointcut("@annotation(com.amat0urheu.annotation.OperateLog)")
    public void logAspect() {

    }


    @Before("logAspect()")
    public void test(JoinPoint joinPoint) {
        String username=SecurityContextHolder.getContext().getAuthentication().getName();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //获取目标对象上的Method对象
        Method method = methodSignature.getMethod();
        String[] parameterNames = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        String params="";
        OperateLog operateLog = method.getAnnotation(OperateLog.class);
        //0不插入参数 1 插入参数
        if(!operateLog.description().equals("0")) {
            for (int i = 0; i < args.length; i++) {
                if (parameterNames[i] != null & args[i] != null) {
                    params = params + (parameterNames[i] + ":" + args[i] + " ");
                }
            }
        }
        OperationLog operationLog = new OperationLog();
        operationLog.setUsername(username);
        operationLog.setAction(operateLog.action());
        operationLog.setParams(params);
        operationLog.setOperateTime(new Date());

        logService.inserSysLog(operationLog);
    }
}